import { useEffect, useRef } from 'react';
import { Button, Card, Space } from 'antd';
import { create } from 'zustand';
import { produce } from 'immer';

type StoreType = {
	obj: { son: { num: number } };
	increment: () => void;
};

const useStore = create<StoreType>((set) => ({
	obj: {
		son: {
			num: 10
		}
	},

	increment: () => {
		const value = produce({ obj: { son: { num: 100 } } }, (state) => {
			console.log('=====', JSON.parse(JSON.stringify(state.obj)));
			++state.obj.son.num;
		});
		set((state) =>
			produce(state, (data) => {
				++data.obj.son.num;
			})
		);
	}

	// increment: () =>
	// 	set((state) => {
	// 		return {
	// 			obj: { ...state.obj, son: { ...state.obj.son, num: state.obj.son.num + 1 } }
	// 		};
	// 	})
}));

const Base = () => {
	const increment = useStore((state) => state.increment);
	const obj = useStore((state) => state.obj);

	const value = useRef(useStore.getState().obj);
	useEffect(() => {
		useStore.subscribe((state) => (value.current = state.obj));
	}, []);
	return (
		<Card>
			<Space>
				<p>num: {obj.son.num}</p>
				<p>value: {value.current.son.num}</p>
			</Space>
			<Button onClick={() => increment()}>+1</Button>
			<Button
				onClick={() => {
					console.log('value: ', value.current.son.num);
				}}
			>
				getValue
			</Button>
		</Card>
	);
};

export default Base;
